# encoding: utf-8

require_relative 'lib/token_pair'
require_relative 'lib/gen_qr'
require_relative 'lib/gen_pdf'

class Imeji < Sinatra::Base
  set app_file: __FILE__

  register Sinatra::ConfigFile
  config_file File.join(root, 'config', 'config.yml')

  use Rack::Session::Pool, expire_after: 86400 # 1 day

  set layout: 'layout'
  set haml: { format: :html5 }

  before do
    @client = Google::APIClient.new(
      authorization: :oauth_2,
      host: settings.oauth_host,
      http_adapter: HTTPAdapter::NetHTTPAdapter.new
    )
    credentials = (ENV['RACK_ENV'] == 'production' ? settings.production : settings.development)
    @client.authorization.client_id = credentials['oauth_client_id']
    @client.authorization.client_secret = credentials['oauth_client_secret']
    @client.authorization.scope = settings.oauth_scope
    @client.authorization.redirect_uri = to '/oauth2callback'
    @client.authorization.code = params[:code] if params[:code]
    @client.authorization.update_token! session[:token].to_hash if session[:token]
    @plus = @client.discovered_api 'plus', 'v1'
    redirect to '/oauth2' unless @client.authorization.access_token || request.path_info =~ /^\/oauth2/ || request.path_info =~ /^\/qr/
  end

  get '/oauth2callback' do
    @client.authorization.fetch_access_token!
    unless session[:token]
      token_pair = TokenPair::TokenPair.new
      token_pair.update_token!(@client.authorization)
      session[:token] = token_pair
      p token_pair
    end
    redirect to '/'
  end

  get '/' do
    data = JSON.parse @client.execute(@plus.people.get, userId: 'me').response[2][0] # magic numbers to extract json data from response
    if data['error'] # probably there is no google plus account assigned to google account
      haml :account_miss, locals: { auth_uri: @client.authorization.authorization_uri.to_s }
    else
      @name = data['displayName']
      @url  = data['url']
      @img  = data['image']['url']
      @qr   = '/qr/' + Base64.encode64(data['url'])
      haml :index
    end
  end

  get '/logout' do
    session.delete :token
    redirect to('/')
  end

  get '/oauth2' do
    haml :signin, locals: { auth_uri: @client.authorization.authorization_uri.to_s }
  end

  get '/badge.pdf' do
    data = JSON.parse @client.execute(@plus.people.get, userId: 'me').response[2][0] # magic numbers to extract json data from response
    img = GenQR::QR.new(data['url'], size: 20, dark: 0x000000, bright: 0xffffff).png
    content_type 'application/pdf'
    GenPDF::Badge.new(data['displayName'], image: img).pdf
  end

  get '/qr/:decode' do
    content_type 'image/png'
    GenQR::QR.new(Base64.decode64(params[:decode]), size: settings.qr['pix_size'], dark: settings.qr['dark_color'], bright: settings.qr['bright_color']).png
  end

  get '/qr_hi/:decode' do
    content_type 'image/png'
    GenQR::QR.new(Base64.decode64(params[:decode]), size: 20, dark: 0x000000, bright: 0xffffff).png
  end
end
